package com.rxt.thermopro.adapter

import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.rxt.thermopro.R
import com.rxt.thermopro.bean.BluetoothBean
import kotlinx.android.synthetic.main.item_view_bluetooth.view.*

class BluetoothAdapter(var list: MutableList<BluetoothBean>) :
    RecyclerView.Adapter<BluetoothAdapter.MyViewHolder>() {

    inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

    }

    var onClick: OnItemClickListener? = null

    fun setOnItemClick(onItemClickListener: OnItemClickListener) {
        this.onClick = onItemClickListener
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val itemView =
            LayoutInflater.from(parent.context).inflate(R.layout.item_view_bluetooth, parent, false)
        itemView.setOnClickListener {

        }
        return MyViewHolder(itemView)
    }

    override fun getItemCount(): Int {
        return list.size
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        val deviceName = list[position].name
        holder.itemView.tv_name.text =
            if (deviceName?.contains("TP960R", true) == true)
                deviceName.replace("TP960R","TP960") else deviceName
//        holder.itemView.tv_address.text = list[position].address
        holder.itemView.deviceIcon.setImageResource(list[position].deviceIcon)
        holder.itemView.viewAdd.setOnClickListener {
            onClick?.onItemClick(holder.itemView, position)
        }
    }

    fun add(bean: BluetoothBean) {
        Log.d("112121->adapter", bean.name + "\n" + bean.address)
        list.add(bean)
        notifyDataSetChanged()
    }

    fun hasBlueDevice(address: String?): Boolean {
        var flag = -1
        list.forEach {
            if (it.address == address) {
                flag = 1
            }
        }
        return flag == 1
    }

    interface OnItemClickListener {
        fun onItemClick(view: View, position: Int)
    }

}